package org.lql.chaos.mq.rabbitmq.producer;

import lombok.extern.slf4j.Slf4j;
import org.lql.chaos.mq.rabbitmq.constant.RabbitMQConstant;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author: liangqinglong
 * @date: 2025-08-08 11:06
 * @description:
 **/
@Slf4j
@Service
public class MultiExchangeMessageProducer {

	@Autowired
	@Qualifier("rabbitTemplate")
	private RabbitTemplate rabbitTemplate;

	// 发送 Fanout 消息（广播）
	public void sendFanoutMessage(String message) {
		rabbitTemplate.convertAndSend(RabbitMQConstant.FANOUT_EXCHANGE, "", message);
		log.info("发送 Fanout 消息: {}", message);
	}

	// 发送 Direct 消息（精准路由）
	public void sendDirectMessage(String message) {
		rabbitTemplate.convertAndSend(RabbitMQConstant.DIRECT_EXCHANGE, RabbitMQConstant.DIRECT_ROUTING_KEY, message);
		log.info("发送 Direct 消息: {}, 路由键: {}", message, RabbitMQConstant.DIRECT_ROUTING_KEY);
	}

	// 发送 Topic 消息（模糊路由）
	public void sendTopicMessage(String routingKey, String message) {
		CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
		rabbitTemplate.convertAndSend(RabbitMQConstant.TOPIC_EXCHANGE, routingKey, message, correlationData);
		log.info("发送 Topic 消息: {}, 路由键: {}", message, routingKey);
	}

	public void sendPersistentMessage(String message) {
		MessageProperties messageProperties = new MessageProperties();
		// 设置消息持久化模式
		messageProperties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
		Message messages = new Message(message.getBytes(), messageProperties);
		rabbitTemplate.convertAndSend(RabbitMQConstant.PERSISTENT_EXCHANGE, RabbitMQConstant.PERSISTENT_ROUTING_KEY, messages);
		log.info("发送 Persistent 消息: {}", message);
	}

	public void sendAlternateMessage(String message) {
		MessageProperties messageProperties = new MessageProperties();
		messageProperties.setMessageId(UUID.randomUUID().toString());
		// 添加自定义属性
		Message messages = new Message(message.getBytes(), messageProperties);
		rabbitTemplate.convertAndSend(RabbitMQConstant.DEFAULT_EXCHANGE, RabbitMQConstant.ALTERNATE_ROUTING_KEY, messages);
		log.info("发送 Alternate 延迟消息: {}", message);
	}

}
